package com.learn.hd.select;

import java.util.Arrays;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description 选择排序------堆排序
 * @date 2019/7/15
 */
public class HeapSort {

    public static void main(String[] args) {

        int[] array = new int[]{ 4, 6, 1, 9, 12, 45, 19, 100, 7};

        int length = array.length;
        //找到倒数第一个非叶子节点， 构造大顶堆
        for (int i = array.length/2-1; i >= 0; i--) {
            adjustHeap(array, i, length);
        }

        //交换第一个元素和最后一个，把最大值移到最后
        for (int i = array.length-1; i > 0 ; i--) {
            swap(array, 0, i);
            adjustHeap(array, 0, i);
        }

        System.out.println(Arrays.toString(array));
    }

    private static void adjustHeap(int[] array, int i, int length) {
        for (int j = 2*i+1; j < length ; j = 2*j+1) {

            if (j+1 < length && array[j] < array[j+1]) {
                j++;
            }

            if (array[i] < array[j]) {
                swap(array, i, j);
                i = j;
            } else {
                break;
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
